package com.tgy.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: tgy
 * @Date: 12/21/20 3:14 PM
 *
 * https://leetcode-cn.com/problems/3sum/
 */
public class _15_三数之和_01 {

    public List<List<Integer>> threeSum(int[] nums) {

        ArrayList<List<Integer>> rets = new ArrayList<>();

        if (nums == null || nums.length == 0) {

            return rets;
        }

        LinkedList<Integer> retNums = new LinkedList<>();

        Arrays.sort(nums);

        int left = 0,right = nums.length - 1,sum = 0;

        for (int i = 0; i < nums.length - 2; i++) {

            if (nums[i] > 0) {
                break;
            }

            if (i > 0 && nums[i - 1] == nums[i]) {

                continue;
            }

            left = i + 1;
            right = nums.length - 1;
            while (left < right) {


                sum = nums[left] + nums[i] + nums[right];

                if (sum == 0) {

                    rets.add(new ArrayList<>(Arrays.asList(nums[i],nums[left],nums[right])));
                    left++;
                    right--;

                }else if (sum > 0) {

                    right--;
                }else if (sum < 0) {

                    left++;
                }

                if (sum <= 0) {

                    while (left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                }

                if (sum >=0) {

                    while (left < right && nums[right] == nums[right + 1]) {

                        right--;
                    }
                }

            }
        }

        return rets;
    }


}
